package com.sz.stock.controller;

import com.alibaba.fastjson.JSONObject;
import com.sz.stock.commons.MD5;
import com.sz.stock.commons.PageBean;
import com.sz.stock.commons.ResultBean;
import com.sz.stock.model.Bankcard;
import com.sz.stock.model.Moneytrad;
import com.sz.stock.model.TUser;
import com.sz.stock.service.IBankCardService;
import com.sz.stock.service.ICardApiService;
import com.sz.stock.service.IUserService;
import com.sz.stock.utils.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.util.List;

//用户系统登录 注册 开户 修改密码
@RestController
@RequestMapping("/user")
public class UserController {

    private IUserService iUserService;
    private ICardApiService iCardApiService;
    private IBankCardService iBankCardService;
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setiCardApiService(ICardApiService iCardApiService) {
        this.iCardApiService = iCardApiService;
    }

    @Autowired
    public void setiUserService(IUserService iUserService) {
        this.iUserService = iUserService;
    }

    @Autowired
    public void setiBankCardService(IBankCardService iBankCardService) {
        this.iBankCardService = iBankCardService;
    }

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @RequestMapping("testConnection")
    public void testConnection() {
        System.out.println("====================欢迎调用=======================");
    }

    //登录；
    @RequestMapping("login")
    public ResultBean userLogin(String userphone, String userpwd){
        String upwd = null;
        try {
            upwd = MD5.encoderByMD5(userpwd);       //加密后的密码
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        ResultBean resultBean =  iUserService.login(userphone, upwd);   //验证登录并将结果返回到resultBean保存
        if (resultBean.getData() != null){
            return resultBean;
        }
        return new ResultBean(0,"登录失败，手机号与密码不匹配！",null);
    }


    //根据userid查询到银行卡；
    @RequestMapping("sBankCard")
    public ResultBean searchBankCard(String userid){
        List<Bankcard> list =  iUserService.searchBankcard(userid);
        return new ResultBean(5,"获取银行卡成功！",list);
    }

    //1.注册一个普通用户
    @RequestMapping("/register")
    public ResultBean register(@RequestBody TUser user) {
        int checkphone = iUserService.checkphone(user.getUserphone());
        ResultBean resultBean = new ResultBean();
        if (checkphone <= 0) {
            try {
                String pwd = MD5.encoderByMD5(user.getUserpwd());
                user.setUserpwd(pwd);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            int m = iUserService.register(user);

            if (m > 0) {
                resultBean.setCode(0);
                resultBean.setMsg("注册成功");
            } else {
                resultBean.setCode(-1);
                resultBean.setMsg("注册失败");
            }
        } else {
            resultBean.setCode(-1);
            resultBean.setMsg("该手机号已被注册");
        }
        return resultBean;
    }

    //2.普通用户关联开户
    @RequestMapping("/openAccount")
    @Transactional
    public ResultBean openAccount(@RequestBody TUser user, String bankCardNumber) {
        Integer userid = user.getUserid();
        String username = user.getUsername();
        String userpaypwd = user.getUserpaypwd();
        String usernumberid = user.getUsernumberid();
        try {
            userpaypwd= MD5.encoderByMD5(userpaypwd);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return new ResultBean(-1, "暂时无法验证,请联系管理员", null);
        }
        String redis_user_object = "stock_user_object_userid";
        redis_user_object = redis_user_object.replace("userid",userid.toString());
        String rUser = stringRedisTemplate.boundValueOps(redis_user_object).get();
        TUser tUser = JSONObject.parseObject(rUser, TUser.class);
        if (tUser.getUserrole() == 0) {
            tUser.setUserrole(1);                                           // 设置为已开户
            tUser.setUsernumberid(usernumberid);                            // 设置卡号
            tUser.setUserpaypwd(userpaypwd);                                // 设置支付密码
            tUser.setUserbalance(new BigDecimal(10000));                // 设置余额为 10000
            String bankCardName = "中国银行";    // 此处写死了银行名称
            Bankcard bankcard = new Bankcard();
            bankcard.setBankUserid(userid);
            bankcard.setBankCardbalance(new BigDecimal(10000));
            bankcard.setBankCardnumber(bankCardNumber);
            bankcard.setBankCardname(bankCardName);
            int n  = 0 ;
            try {
                n = iUserService.openAccount(tUser);                        // 更新用户信息
                n += iBankCardService.setBankCard(bankcard);
            } catch(Exception e) {
                e.printStackTrace();
                // 加入下行代码手动回滚
                // @Transactional 为方法加上事务,try catch 捕获到异常手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new ResultBean(-1, "暂时无法验证,请联系管理员", null);
            }
            if (n == 2) {
                return new ResultBean(0, "开户成功!", null);
            } else {
                return new ResultBean(-1, "信息待审核!稍后再试", null);
            }

            //以下内容为真实调用接口验证
            /*String checkCard = iCardApiService.checkCard(username, bankCardNumber, usernumberid);   // 检查银行卡是不是本人的
            JSONObject jsonObject = JSONObject.parseObject(checkCard);             // 解析返回的JSON字符串
            if (checkCard == null || jsonObject == null) {
                return new ResultBean(-1, "暂时无法验证,请联系管理员", null);
            } else if (jsonObject.getJSONObject("resp").getIntValue("code") == 0) {   //验证银行卡成功后code=0
                tUser.setUserrole(1);                                           // 设置为已开户
                tUser.setUsernumberid(usernumberid);                            // 设置卡号
                tUser.setUserpaypwd(userpaypwd);                                // 设置支付密码
                tUser.setUserbalance(new BigDecimal(10000));                // 设置余额为 10000
                String bankCardName = jsonObject.getJSONObject("data").getString("bank_name");    // 获取银行名称
                Bankcard bankcard = new Bankcard();
                bankcard.setBankUserid(userid);
                bankcard.setBankCardbalance(new BigDecimal(10000));
                bankcard.setBankCardnumber(bankCardNumber);
                bankcard.setBankCardname(bankCardName);
                int n  = 0 ;
                try {
                     n = iUserService.openAccount(tUser);                        // 更新用户信息
                     n += iBankCardService.setBankCard(bankcard);
                } catch(Exception e) {
                    e.printStackTrace();
                    // 加入下行代码手动回滚
                    // @Transactional 为方法加上事务,try catch 捕获到异常手动回滚事务
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return new ResultBean(-1, "暂时无法验证,请联系管理员", null);
                }
                if (n == 2) {
                    return new ResultBean(0, "开户成功!", null);
                } else {
                    return new ResultBean(-1, "信息待审核!稍后再试", null);
                }
            } else {
                return new ResultBean(-1, "验证未通过!", null);
            }*/
        } else {
            return new ResultBean(-1, "此账号已开户,请勿重复操作!",null);
        }

    }
    //充值金额
    @RequestMapping("/recharge")
    public ResultBean recharge (BigDecimal money){
        TUser user = null;
        user.setUserbalance(user.getUserbalance().add(money));
        ResultBean resultBean = new ResultBean();
        int m = iUserService.recharge(user);
        if (m > 0) {
            resultBean.setCode(0);
            resultBean.setMsg("充值成功");
        } else {
            resultBean.setCode(-1);
            resultBean.setMsg("充值失败");
        }
        return resultBean;
    }
    /**
     * 发送验证码
     */
//    @GetMapping("sendCode")
//    public String sendCode (String userphone) throws Exception {
//        ResultBean resultBean=new ResultBean();
//        String code = SmsConfig.yt(userphone);
//        iUserService.addCodeToRedis(code);
//        return code;
//    }

    /**
     * 判断验证输入是否正确
     * 调用方法反馈给用户
     */
    @GetMapping(value = "resetPassword")
    public ResultBean register (String userphone, String userupwd, String usercode){
        ResultBean tc = iUserService.register(userphone, userupwd, usercode);
        if (tc.getCode() == 200) {
            return new ResultBean(200, "重置密码成功!", tc);
        } else {
            return new ResultBean(555, "验证码错误,请重新输入!!!!", tc);
        }
    }
    /**
     * 判断修改验证码是否正确
     */
//    @RequestMapping(value = "opencode", method = RequestMethod.GET)
//    public Boolean openCode (@RequestParam("code") String code){
//        return iUserService.isCodeToRedis(code);
//    }

    /**
     * 从redis中取出登录的用户
     */
    @RequestMapping("usermoney")
    public List<TUser> getAllmoney(int userid){
        return iUserService.isPhoneToRedis(userid);
    }

    /**
     * 充值
     */
    @RequestMapping("topup")
    @ResponseBody
    public ResultBean topup(int userid,BigDecimal balance){
        int cz=iUserService.topup(userid,balance);
        if (cz>0){
            return new ResultBean(0,"充值成功",cz);
        }else {
            return new ResultBean(204,"充值失败",cz);
        }
    }

    /**
     * 提现
     */
    @RequestMapping("withdraw")
    public ResultBean withdraw(int userid,BigDecimal balance){
        int cz=iUserService.withdraw(userid,balance);
        if (cz>0){
            return new ResultBean(0,"提现成功",cz);
        }else {
            return new ResultBean(204,"提现失败",cz);
        }
    }

    /**
     * 用原密码修改密码
     */
    @RequestMapping(value = "modification")
    public ResultBean Modification(int userid,String userphone,String olduserpwd,String newuserpwd){
        ResultBean n=iUserService.getModification(userid,userphone,olduserpwd,newuserpwd);
        if (n.getCode()==200) {
            return new ResultBean(200,"修改成功!",n);
        }else {
            return new ResultBean(400,"修改失败!",n);
        }
    }


    @RequestMapping(value = "modifyname")
    public ResultBean ModifName(int userid,String username){
        ResultBean cs=iUserService.getModifyName(userid,username);
        if (cs.getCode()==200) {
            return new ResultBean(200,"修改成功!",cs);
        }else {
            return new ResultBean(400,"修改失败!",cs);
        }
    }


    /**
     * 通过用户ID 查询指定银行卡信息
     */
    @RequestMapping(value = "/selectBankCardByUserID")
    public Bankcard selectBankCardByUserID(@RequestParam(value = "userid" ,required = false) int userid){
        Bankcard bankcard = iBankCardService.selectBankCard(userid);
        return bankcard;
    }

    /**
     * 通过用户ID 查询用户信息
     */
    @RequestMapping(value = "/selectTUserByUserID")
    public TUser selectTUserByUserID(@RequestParam(value = "userid" ,required = false) int userid){
        TUser tUser = iUserService.selectTUser(userid);
        return tUser;
    }

    /**
     * 通过id查询该用户的交易记录
     * 并分页
     * @param userid
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("list")
    public PageBean<Moneytrad> getAllCarByid(int userid,int pageIndex, int pageSize){
        return iUserService.getAllCarByid(userid,pageIndex,pageSize);
    }



}
